package com.da.lon.wang.xlg.adapter;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.da.lon.wang.xlg.MyApplication;
import com.da.lon.wang.xlg.R;
import com.da.lon.wang.xlg.activity.ProductsActivity;
import com.da.lon.wang.xlg.bean.CartBean.MResult.CartResult;
import com.da.lon.wang.xlg.bean.CartBean.MResult.CartResult.CartValue;
import com.da.lon.wang.xlg.bean.CartUpDateBean;
import com.da.lon.wang.xlg.constants.PreferencesConfig;
import com.da.lon.wang.xlg.constants.XLGConstants;
import com.da.lon.wang.xlg.fragment.CartLienser;
import com.da.lon.wang.xlg.http.HttpLoader;
import com.da.lon.wang.xlg.http.HttpLoader.OnWebLoadListener;
import com.da.lon.wang.xlg.util.DialogUtil;
import com.da.lon.wang.xlg.util.PreferenceUtils;
import com.da.lon.wang.xlg.util.XLGDataUtils;

import net.tsz.afinal.http.AjaxParams;

import java.util.ArrayList;
import java.util.List;

public class CartAdapter extends BaseAdapter {
    LayoutInflater inflater;
    private List<CartResult> dataList;
    private List<CartValue> datas;
    private Context context;
    private List<Holder> holders;
    private CartLienser lienser;
    // private boolean flg = false;
    private DialogUtil dialogUtil;

    private HttpLoader<CartUpDateBean> loader;
    private ArrayList<ImageLocation> imageLocations = new ArrayList<CartAdapter.ImageLocation>();
    private Toast mToast;

    public CartAdapter(Context context, List<CartResult> cartList,
                       CartLienser lienser) {
        try {
            this.dataList = cartList;
            this.context = context;
            inflater = LayoutInflater.from(context);
            this.lienser = lienser;
            holders = new ArrayList<>();
            datas = new ArrayList<>();
            dialogUtil = new DialogUtil(context);
            init();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 控件初始化
     */
    private void init() {
        try {
            for (int i = 0; dataList != null && i < dataList.size(); i++) {
                CartResult bean = dataList.get(i);
                List<CartValue> value = bean.getValue();
                for (int j = 0; j < value.size(); j++) {
                    initView(value, j, i, bean);
                }
            }
            init2();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 初始化控件，绑定监听
     *
     * @param value
     * @param j
     */
    private void initView(List<CartValue> value, int j, int i, CartResult bean) {
        Holder holder = new Holder();
        final CartValue cv = value.get(j);
        datas.add(cv);
        View convertView = inflater.inflate(R.layout.ocoffee_cart_list_item,
                null);
        holder.view = convertView;
        holder.nouse = (TextView) convertView.findViewById(R.id.cart_nouse);
        holder.checkbox_bag = (CheckBox) convertView
                .findViewById(R.id.checkbox_bag);
        holder.checkbox_item = (CheckBox) convertView
                .findViewById(R.id.checkbox_item);
        holder.cart_list_title = (ViewGroup) convertView
                .findViewById(R.id.cart_list_title);
        holder.cart_list_tail = convertView
                .findViewById(R.id.cart_list_tail);
        holder.ar = (TextView) convertView.findViewById(R.id.ar);
        holder.name = (TextView) convertView.findViewById(R.id.name);
        holder.poto = (ImageView) convertView.findViewById(R.id.cart_image);
        doWithPoto(holder, cv);
        holder.price = (TextView) convertView.findViewById(R.id.textview1);
        holder.num = (TextView) convertView.findViewById(R.id.edittext);
        holder.add = (Button) convertView.findViewById(R.id.add);
        holder.minus = (Button) convertView.findViewById(R.id.minus);
        holder.attr = (TextView) convertView.findViewById(R.id.textview_attr);
        doWithAttr(holder, cv);
        holder.delete = (TextView) convertView
                .findViewById(R.id.example_row_b_action_2);
        holder.store = i;
        holder.checked = 0;
        holder.checked2 = 0;
        holder.id = cv.getId();
        holder.p = Float.parseFloat(cv.getPone().getPricespe());
        holder.ar.setText(bean.getAr_name());
        holder.name.setText(cv.getName());
        holder.num.setText(cv.getCount());
        holder.price.setText("￥" + cv.getPone().getPricespe());
        String count = cv.getCount() != null ? cv.getCount() : "0";
        holder.n = Integer.parseInt(count);
        doWithStyte(value, holder, j);

        holders.add(holder);
        // 保存每一项所对应的图片在图片集合中的位置
        imageLocations.add(new ImageLocation(holder, i, j));
    }

    /**
     * 对styte控件的操作
     *
     * @param value  value对象
     * @param holder holder对象
     * @param j      下标
     */
    private void doWithStyte(List<CartValue> value, Holder holder, int j) {
        if (value.size() == 1) {
            holder.styte = 0;
        } else {
            int mo = value.size() - 1;
            if (j == 0) {
                holder.styte = 1;
            } else if (j == mo) {
                holder.styte = 3;
            } else {
                holder.styte = 2;
            }
        }
    }

    /**
     * 对attr控件的操作
     *
     * @param holder      holder对象
     * @param CartValue对象
     */
    private void doWithAttr(Holder holder, CartValue cv) {
        String temp = cv.getPone().getProduct_attr_property();
        if ("".equals(temp)) {
            holder.attr.setVisibility(View.GONE);
        } else {
            holder.attr.setVisibility(View.VISIBLE);
            holder.attr.setText(temp);
        }
        if ("1".equals(cv.getIs_fail())) {
            // holder.checkbox_item.setVisibility(View.INVISIBLE);
            // holder.checkbox_item.setText("失效");
            // holder.checkbox_item.setButtonDrawable(new
            // ColorDrawable(Color.TRANSPARENT));
            // holder.checked = 2;
            holder.checkbox_item.setVisibility(View.GONE);
            holder.nouse.setVisibility(View.VISIBLE);
            holder.checked2 = 1;
        } else {
            holder.checked = 0;
        }
    }

    /**
     * 对poto控件的操作
     *
     * @param holder      holder对象
     * @param CartValue对象
     */
    private void doWithPoto(Holder holder, final CartValue cv) {
        holder.poto.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, ProductsActivity.class);
                String product_number = cv.getProduct_number();
                PreferenceUtils.getInstance().SetSettingString(
                        PreferencesConfig.PRODUCT_NUMBER, product_number);
                context.startActivity(intent);
            }
        });

    }

    private void init2() {
        try {
            if (holders != null) {
                for (int i = 0; i < holders.size(); i++) {
                    Holder holder = holders.get(i);
                    set(holder);
                    doWithPrice(holder);
                    switch (holder.styte) {
                        case 0:
                            setAll(holder);
                            break;
                        case 1:
                            setAll(holder);

                            holder.cart_list_tail.setVisibility(View.GONE);
                            break;
                        case 2:
                            holder.cart_list_title.setVisibility(View.GONE);
                            holder.cart_list_tail.setVisibility(View.GONE);
                            setAll(holder);
                            break;
                        case 3:
                            holder.cart_list_title.setVisibility(View.GONE);
                            setAll(holder);
                            break;

                        default:
                            break;
                    }

                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public int getCount() {

        return datas == null ? 0 : datas.size();
    }

    @Override
    public Object getItem(int position) {
        return datas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        try {
            if (position == holders.size() - 1) {
                lienser.can();
            }
            final Holder holder;
            holder = holders.get(position);
            for (ImageLocation location : imageLocations) {
                if (location.holder == holder) {
                    MyApplication.loadImageByPicasso(context, dataList.get(location.i).getValue().get(location.j)
                            .getPone().getBigimage(), null, holder.poto, 0, 0, 0);
                }
            }
            convertView = holder.view;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return convertView;
    }

    public String getIds() {
        StringBuffer buffer = new StringBuffer();
        try {
            for (int i = 0; holders != null && i < holders.size(); i++) {
                Holder h = holders.get(i);
                if (h != null && h.checked == 1) {
                    if (i == holders.size() - 1) {
                        buffer.append(h.id);
                    } else {
                        buffer.append(h.id + ",");
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return buffer.toString();
    }

    private void doWithPrice(final Holder holder) {
        // holder.price.setText("￥" + holder.p);
        holder.minus.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                final float f = holder.n * holder.p;
                if (holder.n > 1) {
                    // flg = false;
                    holder.n--;
                    holder.num.setText(holder.n + "");
                    // setZhi(holder);
                    loader = new HttpLoader<CartUpDateBean>(context,
                            XLGConstants.URL + "Cart-cartupdate",
                            CartUpDateBean.class, 60 * 1000);
                    AjaxParams params = new AjaxParams();

                    params.put("id", MyApplication.getUserId());
                    params.put("deviceId", MyApplication.getDeviceId());
                    params.put("cart_id", holder.id);
                    params.put("count", holder.n + "");

                    params.put("token", XLGDataUtils.encrypt2MD5("Cart"
                            + "2015#$%" + "cartupdate"));
                    loader.setManagerListener(new OnWebLoadListener<CartUpDateBean>() {

                        @Override
                        public void OnStart() {
                            dialogUtil.showDialog();
                        }

                        @Override
                        public void OnError(String error) {
                            dialogUtil.dismissDialog();
                        }

                        @Override
                        public void onSuccess(CartUpDateBean t) {
                            dialogUtil.dismissDialog();
                            if (null != t.getResult()
                                    && t.getResult().getPrice() != null) {
                                holder.p = Float.parseFloat(t.getResult()
                                        .getPrice());
                                holder.price.setText("￥" + holder.p);
                                if (holder.checked == 1) {
                                    lienser.soleChage(-(f - (holder.p * holder.n)));
                                }
                            } else {
                                lienser.soleChage(-holder.p);
                            }
                        }
                    });
                    loader.loadData(params);

                }
            }
        });

        holder.add.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                final float f = holder.n * holder.p;

                loader = new HttpLoader<CartUpDateBean>(context,
                        XLGConstants.URL + "Cart-cartupdate",
                        CartUpDateBean.class, 60 * 1000);
                AjaxParams params = new AjaxParams();

                params.put("id", MyApplication.getUserId());
                params.put("deviceId", MyApplication.getDeviceId());
                params.put("cart_id", holder.id);
                params.put("count", holder.n + 1 + "");
                params.put("token", XLGDataUtils.encrypt2MD5("Cart" + "2015#$%"
                        + "cartupdate"));
                loader.setManagerListener(new OnWebLoadListener<CartUpDateBean>() {

                    @Override
                    public void OnStart() {
                        // dialogUtil.showDialog();
                        holder.add.setEnabled(false);
                    }

                    @Override
                    public void OnError(String error) {
                        // dialogUtil.dismissDialog();
                    }

                    @Override
                    public void onSuccess(CartUpDateBean t) {
                        // dialogUtil.dismissDialog();
                        holder.add.setEnabled(true);
                        if (t != null && "000002".equals(t.getCode())) {
                            holder.num.setText(holder.n + "");
                            showToast(t.getMessage());
                        } else if ("000000".equals(t.getCode())) {
                            holder.num.setText(++holder.n + "");
                            if (null != t.getResult()
                                    && t.getResult().getPrice() != null) {
                                holder.p = Float.parseFloat(t.getResult()
                                        .getPrice());
                                holder.price.setText("￥" + holder.p);
                                if (holder.checked == 1) {
                                    lienser.soleChage(holder.p * holder.n - f);
                                }
                            } else {
                                lienser.soleChage(holder.p);
                            }
                        }
                    }
                });
                loader.loadData(params);
            }
        });

    }

    private void setAll(final Holder holder) {
        holder.delete.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                lienser.delete(holder.id);
            }
        });

        holder.checkbox_bag
                .setOnCheckedChangeListener(new OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(CompoundButton arg0,
                                                 boolean arg1) {
                        for (int i = 0; holders != null && i < holders.size(); i++) {
                            if (holders.get(i).store == holder.store) {
                                if (arg1) {
                                    if (holders.get(i).checkbox_item != null
                                            && holders.get(i).checkbox_item
                                            .getVisibility() == View.VISIBLE) {
                                        holders.get(i).checkbox_item
                                                .setChecked(true);
                                    }
                                } else {
                                    if (holders.get(i).checkbox_item != null) {
                                        holders.get(i).checkbox_item
                                                .setChecked(false);
                                    }
                                }
                            }
                            isAll();
                        }

                    }

                });

    }

    /**
     * 判断全选 要不要选中
     */
    private void isAll() {
        int h = 0;
        int ht = 0;
        try {
            for (int i = 0; holders != null && i < holders.size(); i++) {

                if (holders.get(i).checked == 1) {
                    h++;
                }
                int visibility = holders.get(i).checkbox_item.getVisibility();
                if (visibility == 8) {
                    if (holders.get(i).checked == 1) {
                        h--;
                    }
                    ht++;
                }
            }

            if (h == holders.size() - ht) {
                lienser.selectAll(true);
            } else {
                lienser.selectAll(false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void set(final Holder holder) {
        holder.checkbox_item
                .setOnCheckedChangeListener(new OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(CompoundButton arg0,
                                                 boolean arg1) {
                        int x = 0, y = 0, z = 0;
                        int header = 0;
                        float hh = (float) 0.00;
                        List<Integer> ins = new ArrayList<Integer>();
                        // 计算价格
                        int vis = holder.checkbox_item.getVisibility();
                        if (vis == 0) {
                            hh = holder.p * holder.n;
                        }
                        boolean frist = true;
                        if (arg1) {
                            holder.checked = 1;
                            lienser.soleChage(hh);
                            for (int i = 0; holders != null
                                    && i < holders.size(); i++) {
                                if (holders.get(i).store == holder.store) {
                                    int visibility = holders.get(i).checkbox_item
                                            .getVisibility();
                                    if (visibility == 0) {
                                        y++;
                                        if (frist) {
                                            header = i;
                                            frist = false;
                                        }
                                        if (holders.get(i).checked == 1) {
                                            x++;
                                        }
                                    }
                                    if (holders.get(i).checked2 == 2) {
                                        z++;
                                    }
                                }
                            }
                            if (x == y - z) {
                                holders.get(header).checkbox_bag
                                        .setChecked(true);
                            }

                        } else {
                            holder.checked = 0;
                            lienser.soleChage(-hh);
                            for (int i = 0; i < holders.size(); i++) {
                                if (holders.get(i).store == holder.store) {
                                    y++;
                                    if (frist) {
                                        header = i;
                                        frist = false;
                                    }
                                    int visibilit = holders.get(i).checkbox_item
                                            .getVisibility();
                                    if (holders.get(i).checked == 0
                                            && holders.get(i).store == holder.store
                                            && visibilit == 0) {
                                        x++;
                                    } else {
                                        ins.add(i);
                                    }
                                }

                            }
                            if (x == 1) {
                                holders.get(header).checkbox_bag
                                        .setChecked(false);
                                for (int i = 0; ins != null && i < ins.size(); i++) {
                                    holders.get(ins.get(i)).checkbox_item
                                            .setChecked(true);
                                }
                            } else {

                            }

                        }
                        // 判断全选 选不选中
                        isAll();
                    }

                });

    }

    public void showToast(String text) {
        if (mToast == null) {
            mToast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
        } else {
            mToast.setText(text);
            mToast.setDuration(Toast.LENGTH_SHORT);
        }
        mToast.show();
    }

    public void selectAll(boolean all) {
        try {
            for (int i = 0; null != holders && i < holders.size(); i++) {
                holders.get(i).checkbox_bag.setChecked(all);
                if (holders.get(i).checkbox_item.getVisibility() == 0) {
                    holders.get(i).checkbox_item.setChecked(all);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class ImageLocation {
        Holder holder;
        int i;
        int j;

        public ImageLocation(Holder holder, int i, int j) {
            this.holder = holder;
            this.i = i;
            this.j = j;
        }

    }

    class Holder {
        View view;
        CheckBox checkbox_bag;
        CheckBox checkbox_item;
        ViewGroup cart_list_title;
        TextView price;
        Button minus;
        Button add;
        TextView num;
        View cart_list_tail;
        int store;
        int checked;
        int checked2;
        int n;
        float p;
        float shui;
        float taxrate;
        int styte;
        ImageView poto;
        TextView ar;
        TextView name;
        TextView bina;
        TextView delete;
        TextView attr;
        TextView shuishou;
        String id;
        TextView nouse;
    }
}
